<template>
  <md-nav-bar title="报名" />
  <view class="container">
    <uni-forms ref="form" :modelValue="data.formData" :rules="data.rules" label-position="top" label-width="100">
      <uni-forms-item label="证件类型" name="id_type" required>
        <view class="form-item" style="padding: 0">
          <uni-data-select
            v-model="data.formData.id_type"
            :localdata="data.idTypeList"
            :clear="false"></uni-data-select>
        </view>
      </uni-forms-item>
      <uni-forms-item
        :label="data.formData.id_type == 1 ? '身份证信息面' : '证件照'"
        name="front_img"
        required
        :rules="[{ required: true, errorMessage: `请上传${data.formData.id_type == 1 ? '身份证信息面' : '证件照'}` }]">
        <view class="form-item">
          <uni-file-picker
            return-type="object"
            file-mediatype="image"
            :imageStyles="{ width: '200rpx', height: '140rpx' }"
            v-model="data.formData.front_img"
            @select="e => handleUpload(e, 'front_img')">
            <md-icon type="bg" name="id_front" width="200" height="140" />
          </uni-file-picker>
        </view>
      </uni-forms-item>
      <uni-forms-item v-if="data.formData.id_type == 1" label="身份证国徽面" name="back_img" required>
        <view class="form-item">
          <uni-file-picker
            return-type="object"
            file-mediatype="image"
            :imageStyles="{ width: '200rpx', height: '140rpx' }"
            v-model="data.formData.back_img"
            @select="e => handleUpload(e, 'back_img')">
            <md-icon type="bg" name="id_back" width="200" height="140" />
          </uni-file-picker>
        </view>
      </uni-forms-item>
      <uni-forms-item label="姓名" name="truename" required>
        <view class="form-item flex-c" style="padding: 0 20rpx 0 0">
          <uni-easyinput type="text" v-model="data.formData.truename" placeholder="请输入姓名" :input-border="false" />
        </view>
      </uni-forms-item>
      <uni-forms-item label="性别" name="sex" required>
        <view class="form-item">
          <uni-data-checkbox v-model="data.formData.sex" :localdata="data.sex"></uni-data-checkbox>
        </view>
      </uni-forms-item>
      <uni-forms-item label="证件号" name="idcard" required>
        <uni-easyinput type="text" v-model="data.formData.idcard" placeholder="请输入证件号" :input-border="false" />
      </uni-forms-item>
      <uni-forms-item label="出生日期" name="birth" required>
        <uni-datetime-picker type="date" :clear-icon="false" v-model="data.formData.birth" :border="false" />
      </uni-forms-item>
      <uni-forms-item label="年龄" name="age" required>
        <uni-easyinput type="number" v-model="data.formData.age" placeholder="请输入年龄" :input-border="false" />
      </uni-forms-item>
      <uni-forms-item label="联系电话" name="mobile" required>
        <uni-easyinput
          type="number"
          v-model="data.formData.mobile"
          placeholder="请输入联系电话"
          :input-border="false" />
      </uni-forms-item>
      <uni-forms-item
        label="验证码"
        name="sms_code"
        required
        :rules="[
          {
            required: data.sign_team_id == -1,
            errorMessage: '请输入验证码',
          },
        ]">
        <view class="flex-l">
          <uni-easyinput
            type="number"
            v-model="data.formData.sms_code"
            placeholder="请输入验证码"
            :input-border="false" />
          <view class="countdown m-left-20" @click="handleGetCode">
            <text v-show="!data.countdownStatus">获取验证码</text>
            <uni-countdown
              v-if="data.countdownStatus"
              :show-day="false"
              :show-hour="false"
              :show-minute="false"
              :second="data.second"
              :show-colon="false"
              @timeup="timeup" />
          </view>
        </view>
      </uni-forms-item>
      <uni-forms-item label="紧急联系人" name="contact" required>
        <uni-easyinput
          type="text"
          v-model="data.formData.contact"
          placeholder="请输入紧急联系人"
          :input-border="false" />
      </uni-forms-item>
      <uni-forms-item label="紧急联系人电话" name="contact_mobile" required>
        <uni-easyinput
          type="number"
          v-model="data.formData.contact_mobile"
          placeholder="请输入紧急联系人电话"
          :input-border="false" />
      </uni-forms-item>
    </uni-forms>
    <!-- 提交按钮 -->
    <view class="m-top-40">
      <md-button
        :color="data.configInfo.button_color1 || '#d92121'"
        :text-color="data.configInfo.button_color1_text || '#ffffff'"
        class="submit"
        @click="submit">
        提交
      </md-button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { onLoad } from '@dcloudio/uni-app';
import { reactive, ref } from 'vue';
// 接口
import { check_ocr_identity, send_sms, singleSign, uploadImage, userSignConfig } from '@/api';
// 工具
import { formatSignSubmitValue } from '../registration/util';
import { Toast } from '@/utils/util';

const data = reactive<any>({
  configInfo: {},
  active_id: -1,
  formData: {
    truename: '',
    idcard: '',
    sex: 1,
    birth: null,
    id_type: 1,
    age: '',
    mobile: '',
    sms_code: '',
    contact: '',
    contact_mobile: '',
    front_img: {},
    back_img: {},
    refer_code: '',
  },
  memberList: [], // 成员添加
  rules: {
    truename: {
      rules: [
        {
          required: true,
          errorMessage: '请输入姓名',
        },
      ],
    },
    idcard: {
      rules: [
        {
          required: true,
          errorMessage: '请输入身份证',
        },
      ],
    },
    sex: {
      rules: [
        {
          required: true,
          errorMessage: '请选择性别',
        },
      ],
    },
    birth: {
      rules: [
        {
          required: true,
          errorMessage: '请选择出生日期',
        },
      ],
    },
    age: {
      rules: [
        {
          required: true,
          errorMessage: '请输入年龄',
        },
      ],
    },
    id_type: {
      rules: [
        {
          required: true,
          errorMessage: '请选择证件类型',
        },
      ],
    },
    mobile: {
      rules: [
        {
          required: true,
          errorMessage: '请输入联系电话',
        },
      ],
    },
    contact: {
      rules: [
        {
          required: true,
          errorMessage: '请输入紧急联系人',
        },
      ],
    },
    contact_mobile: {
      rules: [
        {
          required: true,
          errorMessage: '请输入紧急联系人电话',
        },
      ],
    },
    back_img: {
      rules: [{ required: true, errorMessage: '请上传身份证国徽面' }],
    },
  },
  sex: [
    {
      text: '男',
      value: 1,
    },
    {
      text: '女',
      value: 2,
    },
  ],
  idTypeList: [], // 证件类型下拉
  signTips: '', // 提交报名提示信息
  countdownStatus: false, // 是否开始倒计时
  second: 0, // 验证码倒计时
  from: '', // 从哪个页面过来的
});

const form = ref<any>(null);
const openType = ref('page');

// 点击获取验证码
const handleGetCode = () => {
  if (data.countdownStatus) return;
  if (!data.formData?.mobile) {
    Toast('请填写手机号再进行操作！');
    return;
  }
  fetchSendSms(data.formData?.mobile);
};

// 倒计时结束回调
const timeup = () => {
  data.countdownStatus = false;
};

// 回退页面逻辑
const cbPage = () => {
  if (openType.value === 'share') {
    uni.switchTab({ url: '/pages/index/index' });
  } else {
    uni.navigateBack();
    // 返回的页面执行刷新
    uni.setStorageSync('isRefresh', 1);
  }
};

// 触发提交表单
const submit = async () => {
  try {
    const res = await form.value?.validate();
    uni.showModal({
      title: '提示',
      content: data?.signTips || '是否确认提交报名信息',
      confirmText: '确认提交',
      cancelText: '再修改',
      success: s => {
        if (s.confirm) {
          singleSign({
            active_id: data.active_id,
            ...formatSignSubmitValue(res),
          }).then(res => {
            uni.showModal({
              title: '提示',
              content: res?.msg || '报名成功',
              showCancel: false,
              success: res => {
                if (res.confirm) {
                  cbPage();
                }
              },
            });
          });
        }
      },
    });
  } catch (e: any) {
    //TODO handle the exception
    console.log('表单错误信息：', e);
    e?.length && Toast(e?.[e?.length - 1]?.errorMessage);
  }
};

/**
 * 上传相关
 */
const handleUpload = (e: any, type: string) => {
  let { tempFilePaths } = e;
  uni.showLoading({
    title: '图片上传中...',
    mask: true,
  });
  uploadImage({ filePath: tempFilePaths[0], formData: { category: 'sign', active_id: data.active_id } })
    .then(async res => {
      const obj = {
        url: res.data.url,
        extname: 'png',
        name: type + '.png',
      };
      if ([1, 2, 3, 4, 9].includes(data.formData.id_type) && type === 'front_img') {
        const info = await fetchCheckOcrIdentity(res?.data?.url);
        data.formData = { ...data.formData, ...info };
      }
      data.formData[type] = obj;
    })
    .catch(e => {
      data.formData[type] = {};
    })
    .finally(() => {
      uni.hideLoading();
    });
};

/**
 * 接口相关
 */
// 获取其他下拉数据
const fetchUserSignIndex = async () => {
  try {
    const res = await userSignConfig();
    data.idTypeList = res.data?.id_type || [];
    data.signTips = res.data.sign_tips;
    return true;
  } catch (error) {}
  return false;
};

// 校验身份证图片
const fetchCheckOcrIdentity = async (front_img: string) => {
  try {
    const res = await check_ocr_identity({ front_img, id_type: data.formData.id_type });
    return res.data;
  } catch (error) {}
  return undefined;
};

// 手机获取验证码
const fetchSendSms = async (mobile: string) => {
  try {
    const res = await send_sms({ mobile, event: 'single_sign' });
    Toast(res?.msg || '发送成功');
    data.countdownStatus = true;
    data.second = 59;
  } catch (error) {}
};

onLoad(option => {
  const configInfo = uni.getStorageSync('configInfo') ? JSON.parse(uni.getStorageSync('configInfo')) : '';
  if (configInfo) {
    data.configInfo = configInfo;
  }
  data.active_id = option?.active_id;
  data.from = option?.from; // 从哪里跳转过来的 share | defalut(默认不传)

  // 通过什么方式打开的页面 page | share
  openType.value = option?.openType || 'page';
  // 接口调用
  uni.showLoading({
    title: '加载中',
  });
  Promise.all([fetchUserSignIndex()]).finally(() => {
    uni.hideLoading();
  });
});
</script>

<style lang="scss" scoped>
.container {
  padding: 30rpx;
  .forms-item-label {
    height: 36px;
    line-height: 36px;
    padding-bottom: 10px;
    font-size: 14px;
    color: #606266;
  }
  .text-label {
    height: 28px;
    line-height: 28px;
    font-size: 14px;
    color: #606266;
    padding-bottom: 8px;
    box-sizing: border-box;
  }
  .form-item {
    background: white;
    border-radius: 10rpx;
    padding: 10rpx 0 10rpx 10px;
    &.text-content {
      height: 30px;
      line-height: 30px;
      font-size: 14px;
    }
  }
  .form-item-content {
    padding: 16rpx;
    background: white;
  }
  .form-item-row {
    position: relative;
    .del-button {
      position: absolute;
      right: 0;
      top: 0;
    }
  }
  .member-list {
    .del-btn {
      position: absolute;
      top: 0;
      right: 0;
    }
    .member-item {
      position: relative;
      width: 100%;
      height: 80rpx;
      background: #f7f7f7;
      border-radius: 10rpx;
      font-size: 28rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 24rpx;
      box-sizing: border-box;
      margin-bottom: 20rpx;
    }
  }
  .add {
    width: 100%;
    height: 80rpx;
    line-height: 80rpx;
    background: #f7f7f7;
    border-radius: 10rpx;
    color: #b3b3b3;
    font-size: 28rpx;
    text-align: center;
    &.white {
      background: white;
      color: $title;
    }
  }

  .countdown {
    height: 35px;
    padding: 0 20px;
    border: 1px solid $lineColor;
    line-height: 35px;
    border-radius: 8rpx;
    box-sizing: border-box;
  }
}
</style>
